<?php
class login extends Admin {

    public function index( $c ) {
        if ( $this->user ) {
            $this->redirect( $this->mc_url( 'main' ) );
        }
        include $this->display( $c );
    }

    public function verify() {
        $this->Image()->Verify();
    }

    public function loging() {

        if ( isset( $_POST[ 'verify' ] ) && strtolower( $_POST[ 'verify' ] ) != $_SESSION[ "verify" ] ) {
            $this->error( '验证码错误!' );
        }

        $author = trim( $_POST[ 'author' ] );
        $pass = mc_md5( trim( $_POST[ 'pass' ] ) );
        $data = array( 'author' => $author );

        $user = mc_model( 'user' );
        if ( !$result = $user->is_user( $data ) ) {
            $this->error( "{$author}账号不存在!" );
        }
        if ( $result[ 'pass' ] != $pass ) {
            $this->error( "密码错误!" );
        }
        if ( $result[ 'status' ] ) {
            $this->error( "账号已被锁定!" );
        }
        if ( $user->is_admin( $result[ 'sid' ] ) ) {
            $this->error( "您的帐号无权限!" );
        }

        // 更新登录时间IP
        $dateline = time();
        $user->update( $data, array( 'lastdate' => $dateline, 'lastip' => mc_server( 'ip' ) ) );

        $expire = 0;
        if ( isset( $_POST[ 'remember' ] ) ) {
            $expire = !mc_setting( 'cookie_time' ) ? $_POST[ 'remember' ] : ( mc_setting( 'cookie_time' ) * 3600 * 24 + time() );
        }

        // 写入登录cookie
        $cookie_value = "{$result[ 'author' ]}|{$result[ 'id' ]}|{$expire}|{$dateline}";
        $cookie_value = mc_md5( $cookie_value, 'encode' );
        setcookie( APP_COOKIE, $cookie_value, $expire, '/', APP_COOKIE_DOMAIN );
        $this->success( "登录成功!" );
    }


    public function logout() {
        setcookie( APP_COOKIE, '', time() - mc_setting( 'cookie_time' ) * 3600 * 24, '/', APP_COOKIE_DOMAIN );
        $this->redirect( $this->mc_url() );
    }
}